<?php
namespace yunj\validate;

use yunj\Validate;
use yunj\builder\YunjTable as YTBuilder;

class YunjTable extends Validate {

    protected $rule = [
        'builderId' => 'require',
        'builderAsyncType' => 'require|in:stateCount,count,items,event,export',
    ];

    protected $message = [
        'builderId.require' => '访问错误',
        'builderAsyncType.require' => '[builderAsyncType]参数缺失',
        'builderAsyncType.in' => '[builderAsyncType]参数错误',
    ];

    protected $scene = [
        'AsyncRequest'=>['builderId','builderAsyncType'],
    ];

    protected function handleData(array $rawData,$scene): array {
        $data=$rawData;
        if($scene=='AsyncRequest'){
            $this->checkFilter($data);
            $this->checkSort($data);
            switch ($data['builderAsyncType']){
                case 'stateCount':
                    $this->handleDataByStateCount($data);
                    break;
                case 'count':
                    $this->handleDataByCount($data);
                    break;
                case 'items':
                    $this->handleDataByItems($data);
                    break;
                case 'event':
                    $this->handleDataByEvent($data);
                    break;
                case 'export':
                    $this->handleDataByExport($data);
                    break;
            }
        }
        return $data;
    }

    private function handleDataByStateCount(&$data){
        return $data;
    }

    private function handleDataByCount(&$data){
        // filter补充ids
        $data['filter']['ids']=[];
        return $data;
    }

    private function handleDataByItems(&$data){
        //验证page、limit
        if(!isset($data['page'])||!isset($data['limit'])) throw_error_json('请求参数异常');
        $page=$data['page'];
        $limit=$data['limit'];
        if(!is_positive_integer($page)||!is_positive_integer($limit)) throw_error_json('请求参数类型异常');
        $data['limit_length']=round($limit,0);
        $data['limit_start']=round(($page-1)*$data['limit_length'],0);
        // filter补充ids
        $data['filter']['ids']=[];
        return $data;
    }

    private function handleDataByEvent(&$data){
        if(!isset($data['filter']['event'])) throw_error_json('请求参数异常');
        $data['filter']['ids']=isset($data['filter']['ids'])&&is_array($data['filter']['ids'])?$data['filter']['ids']:[];
        return $data;
    }

    private function handleDataByExport(&$data){
        //验证 num、limit
        if(!isset($data['num'])) throw_error_json('请求参数异常');
        $page=$data['num'];
        $limit=YTBuilder::EXPORT_LIMIT;
        if(!is_positive_integer($page)) throw_error_json('请求参数类型异常');
        $data['limit_length']=round($limit,0);
        $data['limit_start']=round(($page-1)*$data['limit_length'],0);
        return $data;
    }

    private function checkFilter(&$data){
        // 以下请求类型不检查filter
        $excludeTypeArr=['stateCount'];
        if(in_array($data['builderAsyncType'],$excludeTypeArr)) return $data;

        if(!isset($data["filter"])) throw_error_json('[filter]参数缺失');
        $data['filter']=is_array($data['filter'])?$data['filter']:json_decode($data['filter'],true);
        //$this->checkFilterState($data);
        $this->checkFilterIds($data);
        return $data;
    }

    // TODO 弃用
    private function checkFilterState(&$data){
        // 以下请求类型不检查filter的state参数
        $excludeTypeArr=['event'];
        if(!in_array($data['builderAsyncType'],$excludeTypeArr)&&!isset($data['filter']['state'])) throw_error_json('filter请求参数[state]异常');
        return $data;
    }

    private function checkFilterIds(&$data){
        // 以下请求类型需检查filter的ids参数
        $typeArr=['export'];
        if(!in_array($data['builderAsyncType'],$typeArr)) return $data;
        if(!isset($data['filter']['ids'])) throw_error_json('filter请求参数[ids]缺失');
        foreach ($data['filter']['ids'] as $k=>$id){
            $id=filter_sql($id);
            if(!$id==='') throw_error_json('filter请求参数[ids]异常');
            $data['filter']['ids'][$k]=$id;
        }
        return $data;
    }

    private function checkSort(&$data){
        // 以下请求类型需检查sort参数
        $typeArr=['items','export'];
        if(!in_array($data['builderAsyncType'],$typeArr)) return $data;
        if(!array_key_exists('sort',$data)) throw_error_json('[sort]参数缺失');
        $sort=is_array($data['sort'])?$data['sort']:json_decode($data['sort'],true);
        foreach ($sort as $k=>$v){
            if(!$this->regex($k,"alphaDash")) throw_error_json("[sort][{$k}]只能为字母/数字/下划线组合");
            if(!in_array($v,['asc','desc'])) throw_error_json("[sort][{$k}]值只能为asc/desc");
        }
        $data['sort']=$sort;
        return $sort;
    }

}